/*
 * @Autor: 陈科引
 * @Date: 2021-09-02 17:15:19
 * @LastEditTime: 2021-09-09 11:00:37
 * @FilePath: \sybjgl_web\src\pages\Physical\index.js
 * @LastEditors: 陈科引
 * @Description: 
 */
import React, { Component } from 'react'

import {
  SearchOutlined,
  FileAddOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { Form, Col, Row, Input, Button, Popconfirm, Select } from 'antd';
import MyTable from '@/components/MyTable';
import '@/layouts/queryList.css';
import BtnPermission from '@/components/BtnPermission';
// import BtnTs from '@/components/BtnTs';
import EditItem from './EditItem';
import { ygxxApi, institutionsApi } from '@/services/basic';
// import ExportAsExcel from "../Dc/exportAsExcel";
import { Switch } from 'antd';
import {ButtonExport, SelectPositions} from "../../components/BaseComponent/forms";
const InputGroup = Input.Group;
const Option = Select.Option;
class TrainingCourse extends Component {
  constructor(props) {
    super(props)
    // this.excelRef = React.createRef();
    this.state = {
      data: [],//data就是最顶层的数据 它包含records records是每条列表数据的集合 data还包含了其他信息 譬如总页数 当前页等等
      records: [],
      ksdata: [], // 当前科室信息
      jclx: this.props.history.location.pathname.split('/')[2],
      yybm: JSON.parse(sessionStorage.getItem("userInfo")).yybm,
      handlers: {
        create: "create",
        view: "view",
        update: "update",
      }, //定义操作类型
    };
  }
  //组件挂载后为列表请求数据
  componentDidMount = () => {
    this.queryData();
  };

  //页码变化的时候，请求数据
  onChange = (pagination) => {
    this.queryData(pagination);
  };
  //增、改一条数据后刷新列表
  editItemDone = () => {
    this.queryData();
  };

  //增查改、设置操作类型，并传入对应行数据
  setHandler = (handler, record) => {
    this.EditItemRef.showModal(handler, record, this.state.jclx);
  };
  onInstitutionSearch = (value, option) => {
    if (value.charCodeAt(value.length - 1) === 32) {
      value = value.trim();
      institutionsApi.search({ search: `${value}` })
        .then((res) => {
          let institution = res.records.map(item => <Option key={item.yybm} value={item.yybm}>{item.yymc}</Option>);
          this.setState({
            institution: institution,
          })
        })
    }
  }

  //删除一条数据后刷新列表
  deleteItem = (record) => {
    ygxxApi.delete(record.id).then((res) => {
      this.queryData();
    });
  };

  //查找框查找数据
  queryData = (pagination = undefined) => {
    let formData = this.form.getFieldsValue();
    // formData.czsj = formData.czsj && formData.czsj.format("YYYY-MM-DD");
    formData = {
      ...formData,
      rzsj: formData.rzsj && formData.rzsj[0].format('YYYY-MM-DD'),
    }
    ygxxApi.getPage({ formData, pagination }).then((res) => {
      if (res.code === "0") {
        //message.error("此身份证号系统已建档!");
      } else {
        this.setState({ data: res.data, records: res.data.records });
      }
    });
  };

  // 导出
  dc = () => {
    const formData = this.form.getFieldsValue();
    formData.size = 10000;
    // if (this.excelRef.current) {
    //   this.excelRef.current.excelDownload(formData);
    // }
    return new Promise((resolve, reject)=>{
      ygxxApi.getPage({ formData }).then((res) => {
        resolve(res.data.records)
      }).catch(()=>reject());
    })
  }

  // 切换：启用-未启用
  onSwitchChange(val, row) {
    ygxxApi.put({id: row.id, sfzx: (val ? 1 : 0)}).then(res => {
    });
  }

  render() {
    const { handlers } = this.state;
    // const queryFn =  ygxxApi.getPage;
    const onSwitchChange =  this.onSwitchChange;
    // const formData = this.form.getFieldsValue();
    const columns1 = [
      { title: "姓名", dataIndex: "xm" },
      {
        title: "性别", dataIndex: "xb",

        render: (text) => {
          return text === 1 ? "男" : "女";
        },
      },

      { title: "联系电话", dataIndex: "lxdh" },
      { title: "身份证", dataIndex: "sfz" },
      { title: "职位", dataIndex: "sjmc" },
      { title: "工号", dataIndex: "gh" },
      { title: "入职时间", dataIndex: "rzsj" },
      { title: "转正时间", dataIndex: "zzsj" },
      { title: "是否离职", dataIndex: "ztbzmc" },
      // { title: "离职时间", dataIndex: "lzsj" },
      // { title: "离职原因", dataIndex: "lzyy" },
      { title: "薪资", dataIndex: "xz" },
      { title: "银行卡号", dataIndex: "yhkh" },
      { title: "部门名称", dataIndex: "ksmc" },
      { title: "公司名称", dataIndex: "yymc" },
      {
        title: "接取留资", dataIndex: "sfzx", render(val, row) {
          return (<Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={val} onChange={(e)=>{onSwitchChange(e, row)}} />)
        },
        excelRender(val,row){
          return val?"是":"否"
        }
      },

    ];
    const columns = [...columns1,      {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (record) => (
          <span className="handleButton">
            {this.props.permission.edit ? (
                <FormOutlined
                    title="修改"
                    onClick={() => this.setHandler(handlers.update, record)}
                    className="update-button"
                />
            ) : null}
            {this.props.permission.delete ? (
                <Popconfirm
                    title="确认删除?"
                    onConfirm={() => this.deleteItem(record)}
                >
                  <DeleteOutlined className="delete-button" />
                </Popconfirm>
            ) : null}
          </span>
      ),
    },]
    return (
      <div className='queryList'>
        <Form autoComplete='off' ref={(form) => (this.form = form)} layout='inline'>
          <InputGroup className='input-group'>
            <Row>
              <Col span={4} >
                <Form.Item label='人员姓名' name='xm' getValueFromEvent={(event) => event.target.value.replace(/\s+/g, '')}>
                  <Input allowClear placeholder='请输入姓名' />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item label='身份证号' name='sfz'>
                  <Input allowClear placeholder='请输入身份证号' />
                </Form.Item>
              </Col>
              {/* <Col span={4}>
                <Form.Item label='入职日期' name='rzsj'>
                  <DatePicker allowClear />
                </Form.Item>
              </Col> */}
              <Col span={4}>
                <Form.Item label='所属公司' name='yybm'>
                  <Select allowClear
                    placeholder="输入关键字按空格查找"
                    filterOption={false}
                    showSearch={true}
                    onSearch={this.onInstitutionSearch}
                    showArrow={false}

                  >
                    {this.state.institution}
                  </Select>
                </Form.Item>
              </Col>

              <SelectPositions span={4}></SelectPositions>
              <Col span={2}>
                <Button onClick={(e) => this.queryData(e)} icon={<SearchOutlined />} className="search-button r-m-r-6">
                  查询
                </Button>
              </Col>
              <Col span={2}>
                <Button icon={<FileAddOutlined />} className="addButton" onClick={() => this.setHandler('create')}>
                  新增
                </Button>
              </Col>

              <ButtonExport filename="鹏成车邦分公司汇总报表"
                            columns={columns1}
                            // getDateRange={this.getDateRange}
                            queryDataList={this.dc}
              />
              {/*<Col span={2} >*/}
              {/*  <Button onClick={this.dc} className="search-button r-m-r-6">导出</Button>*/}
              {/*</Col>*/}
            </Row>
          </InputGroup>
        </Form>
        <MyTable
          props={{
            columns,
            dataSource: this.state.records,
            data: this.state.data,
            setHandler: this.setHandler,
            onChange: this.onChange,
            permission: this.props.permission,
          }}
        />
        <div>
          <EditItem
            ref={(EditItemRef) => (this.EditItemRef = EditItemRef)}
            editItemDone={this.editItemDone}
            bookRender={this.props.bookRender}
            // modalfoot={this.props.modalfoot}
          />
        </div>
        {/*{<ExportAsExcel*/}
        {/*    ref={this.excelRef}*/}
        {/*    queryFn={queryFn}*/}
        {/*    columns={columns}*/}
        {/*    filename={'鹏成车邦分公司汇总报表'}*/}
        {/*/>}*/}
      </div>

    )
  };

}

export default BtnPermission(TrainingCourse, {
  dataBook: {
    82: "zw", // 职务
  },
})
